package com.sgb.kjwl.view.ui.activity.self.logistics;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.text.Html;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityReleaseBiddingCargoBinding;
import com.sgb.kjwl.model.entity.transport.CargoPublishEntity;
import com.sgb.kjwl.model.entity.transport.GoodsInfoTypeEntity3;
import com.sgb.kjwl.utils.CargoConstant;
import com.sgb.kjwl.utils.Constants;
import com.sgb.kjwl.utils.NumberUtil;
import com.sgb.kjwl.utils.PickerHelper;
import com.swgk.core.util.UserOperating;
import com.sgb.kjwl.view.constant.RequestCode;
import com.sgb.kjwl.view.constant.RouterKey;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.WebEvent;
import com.sgb.kjwl.view.ui.activity.WebActivity;
import com.sgb.kjwl.view.ui.adapter.self.logistics.CargoPublishPersonAdapter;
import com.sgb.kjwl.viewmodel.self.logistics.ReleaseBiddingCargoModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.util.ArrayUtil;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.TimeUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * bidding
 *
 * @author: 杨畔
 * @date: 2020/12/29 11:44
 * @Description: 发布竞价货源
 */
public class ReleaseBiddingCargoActivity extends AppActivity {
    ReleaseBiddingCargoModel viewModel;
    ActivityReleaseBiddingCargoBinding binding;
    //选择器
    private OptionsPickerView<GoodsInfoTypeEntity3> mLoadModePicker;
    private TimePickerView mDatePicker;
    //发货地/收货地列表
    private int mLocationIndex;//选中地址下标
    private List<CargoPublishEntity.LocationEntity> mLocationList;
    private CargoPublishPersonAdapter mLocationAdapter;
    //数据实体类
    private CargoPublishEntity mEntity;

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        viewModel = new ViewModelProvider(this).get(ReleaseBiddingCargoModel.class);
    }

    @Override
    protected void init() {
        binding = DataBindingUtil.setContentView(ReleaseBiddingCargoActivity.this, R.layout.activity_release_bidding_cargo);
        binding.setLifecycleOwner(this);
        binding.tvReleaseCargoProtocol.setText(Html.fromHtml("发布货源即表示您同意"
                + "<font color='#5792FD'>《经营帮货物运输协议》</font>所有内容"));
        //初始化页面
        initPicker();
        initRecycler();
        initEvent();
        initData();
    }

    private void initPicker() {
        //报价截止时间选择器
        mDatePicker = PickerHelper.with(this).getCommonTimeBuild("选择报价截止时间", (date, v) -> {
            long time = DateUtils.getCustomizeDayNight(0, date.getTime()).getTime();
            //设置数据
            mEntity.setBiddingEndTime(time);
            binding.tvReleaseCargoQuotation.setText(DateUtils.stampToDay5(String.valueOf(time)));
        })
                .setType(new boolean[]{true, true, true, false, false, false})
                .setRangDate(Calendar.getInstance(), null)
                .build();
    }

    private void initRecycler() {
        //发货人/收货人列表
        mLocationList = new ArrayList<>();
        mLocationAdapter = new CargoPublishPersonAdapter(mLocationList);
        binding.rvReleaseCargoPerson.setNestedScrollingEnabled(false);
        binding.rvReleaseCargoPerson.setLayoutManager(new LinearLayoutManager(this));
        mLocationAdapter.bindToRecyclerView(binding.rvReleaseCargoPerson);
    }

    private void initEvent() {
        binding.setOnClick(this);
        binding.includeTitle.ivBack.setOnClickListener(this);
        mLocationAdapter.setOnItemClickListener((adapter, view, position) -> {
            mLocationIndex = position;
            CargoPublishPersonActivity.start(ReleaseBiddingCargoActivity.this,
                    mLocationList.get(position), RequestCode.CODE_SEVEN);
        });
        //接口回调
        viewModel.ldPublish.observe(this, this::syncData);
        viewModel.ldHandleType.observe(this, this::initLoadPicker);
        viewModel.ldDistance.observe(this, entity -> {
            //设置总运程数据
            mEntity.setDistance(entity);
            if (entity == null || entity.getTotalDistance() == null) {
                binding.llReleaseCargoDistance.setVisibility(View.GONE);
            } else {
                binding.llReleaseCargoDistance.setVisibility(View.VISIBLE);
                binding.tvReleaseCargoDistance.setText(String.format("约%skm", NumberUtil.trim0(entity.getTotalDistance() / 1000)));
            }
        });
        //跳转回调
        viewModel.ldJump.observe(this, integer -> {
            if (integer == 0) {
                //跳转费用信息
                CargoPublishCostActivity.start(this, mEntity, RequestCode.CODE_THREE);
            }
        });
        //定位回调
        viewModel.ldLocation.observe(this, aBoolean -> {
            mLocationAdapter.notifyDataSetChanged();
            //重算运程
            calculateLineDistance();
        });
    }

    private void initData() {
        String no = getIntent().getStringExtra(RouterKey.NO);
        if (TextUtils.isEmpty(no)) {
            boolean isNormal = getIntent().getBooleanExtra(RouterKey.BOOLEAN, true);
            mEntity = new CargoPublishEntity();
            mEntity.setPattern(isNormal ? 0 : 1);
            initCommon();
        } else {
            viewModel.getDetail(this, no);
        }
        //获取页面数据
        viewModel.getHandleType();

    }

    /**
     * 初始化装卸方式弹窗
     */
    private void initLoadPicker(List<GoodsInfoTypeEntity3> list) {
        //装卸方式选择器
        mLoadModePicker = PickerHelper.with(this).getCommonPicker("选择装卸方式", list, (options1, options2, options3, v) -> {
            GoodsInfoTypeEntity3 entity = list.get(options1);
            mEntity.setLoadModeNo(entity.getNo());
            mEntity.setLoadMode(entity.getName());
            binding.tvReleaseCargoLoadMode.setText(entity.getName());
            //设置列表数据
            viewModel.getLocationListByLoadMode(mLocationList, entity.getNo());
            mLocationAdapter.notifyDataSetChanged();
            //重算运程
            calculateLineDistance();
        });
    }

    /**
     * 编辑货源时同步货源数据使用
     */
    private void syncData(CargoPublishEntity entity) {
        if (entity == null) {
            boolean isNormal = getIntent().getBooleanExtra(RouterKey.BOOLEAN, true);
            mEntity = new CargoPublishEntity();
            mEntity.setPattern(isNormal ? 0 : 1);
            initCommon();
            return;
        }
        mEntity = entity;
        initCommon();
        //同步数据
        syncDate(mEntity);
        syncGoods(mEntity);
        syncCost(mEntity);
        syncOffer(mEntity);
        syncMoreData(mEntity);
        syncContact(mEntity);
        //设置竞价结束时间
        if (mEntity.getPattern() == 1 && mEntity.getBiddingEndTime() != 0) {
            binding.tvReleaseCargoQuotation.setText(DateUtils.stampToDay5(String.valueOf(mEntity.getBiddingEndTime())));
        } else {
            binding.tvReleaseCargoQuotation.setText("");
        }
    }

    /**
     * 设置通用数据
     */
    private void initCommon() {
        //设置标题
        binding.includeTitle.titleView.setText(mEntity.getPattern() == 0 ? "发布普通货运项目" : "发布竞价货运项目");
        binding.llReleaseCargoQuotation.setVisibility(mEntity.getPattern() == 0 ? View.GONE : View.VISIBLE);
        //设置默认数据
        if (TextUtils.isEmpty(mEntity.getCompanyNo())) {
            //设置用户信息
            mEntity.setCompanyNo(UserOperating.getInstance().getTeamOrCompanyNameNo());
            mEntity.setCompany(UserOperating.getInstance().getTeamOrCompanyName());
            mEntity.setContact(UserOperating.getInstance().getUserRealName());
            mEntity.setContactTel(UserOperating.getInstance().getPhone());
        }
        //设置装卸方式
        initDefaultLoadMode();
    }

    /**
     * 初始化默认装卸方式
     */
    private void initDefaultLoadMode() {
        //只有初始发布填写定位数据，历史货源/编辑货源数据不填写
        if (!TextUtils.isEmpty(mEntity.getLoadModeNo())) {
            //编辑货源/历史货源
            binding.tvReleaseCargoLoadMode.setText(mEntity.getLoadMode());
            viewModel.getLocationListByLoadMode(mLocationList, mEntity.getLoadModeNo());
            mLocationAdapter.notifyDataSetChanged();
            //重算运程
            calculateLineDistance();
        } else {
            mEntity.setLoadModeNo("11");
            mEntity.setLoadMode("一装一卸");
            binding.tvReleaseCargoLoadMode.setText(mEntity.getLoadMode());
            viewModel.getLocationListByLoadMode(mLocationList, mEntity.getLoadModeNo());
            viewModel.getCurrentLocation(this);
        }
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_release_cargo_history:
                //选择历史货源
                CargoPublishHistoryActivity.start(this, mEntity.getPattern(), RequestCode.CODE_ZERO);
                break;
            case R.id.ll_release_cargo_load_mode:
                //选择装卸方式
                mLoadModePicker.show();
                break;
            case R.id.ll_release_cargo_load_date:
                //选择装货时间
                BiddingCargoPublishDateActivity.start(this, mEntity, RequestCode.CODE_ONE);
                break;
            case R.id.ll_release_cargo_cargo_info:
                //选择货物信息
                BiddingCargoPublishCargoInfoActivity.start(this, mEntity, RequestCode.CODE_TWO);
                break;
            case R.id.ll_release_cargo_price:
                //选择费用要求
                if (mEntity.getGoodsWeight() == 0) {
                    MToast.showToast(this, "请先填写货物信息");
                } else {
                    BiddingCargoPublishCostActivity.start(this, mEntity, RequestCode.CODE_THREE);
                }
                break;
            case R.id.ll_release_cargo_offer:
                //报价要求
                BiddingCargoPublishOfferActivity.start(this, mEntity, RequestCode.CODE_FOUR);
                break;
            case R.id.ll_release_cargo_quotation:
                //选择报价截止时间
                mDatePicker.show();
                break;
            case R.id.ll_release_cargo_more:
                //选择更多信息
                BiddingCargoPublishMoreActivity.start(this, mEntity, RequestCode.CODE_FIVE);
                break;
            case R.id.ll_release_cargo_contact:
                //联系信息
                BiddingCargoPublishContactActivity.start(this, mEntity, RequestCode.CODE_SIX);
                break;
            case R.id.tv_release_cargo_submit:
                //提交货源
                clearAllFocus();
                if (binding.cbReleaseCargoProtocol.isChecked()) {
                    mEntity.setLocationList(mLocationList);
                    viewModel.releaseCargo(this, binding.tvReleaseCargoSubmit, mEntity);
                } else {
                    MToast.showToast(this, "请先勾选同意经营帮货物运输协议");
                }
                break;
            case R.id.tv_release_cargo_protocol:
                EventBus.getDefault().postSticky(WebEvent.make(EventConstant.EVENT_WEBVIEW, Constants.TRANSPORT_URL));
                WebActivity.start(ReleaseBiddingCargoActivity.this);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) return;
        //历史货源回调
        if (requestCode == RequestCode.CODE_ZERO && data != null) {
            String no = data.getStringExtra(RouterKey.NO);
            viewModel.getDetail(this, no, true);
            return;
        }
        //发货人/收货人回调
        if (requestCode == RequestCode.CODE_SEVEN) {
            syncLocation(data);
            //计算运程
            calculateLineDistance();
            return;
        }
        //货源子页面数据
        if (data == null) return;
        CargoPublishEntity entity = data.getParcelableExtra(RouterKey.DATA);
        if (entity == null) return;
        switch (requestCode) {
            case RequestCode.CODE_ONE:
                syncDate(entity);
                break;
            case RequestCode.CODE_TWO:
                syncGoods(entity);
                break;
            case RequestCode.CODE_THREE:
                syncCost(entity);
                break;
            case RequestCode.CODE_FOUR:
                syncOffer(entity);
                break;
            case RequestCode.CODE_FIVE:
                syncMoreData(entity);
                break;
            case RequestCode.CODE_SIX:
                if (ArrayUtil.isNotNullAndEmpty(entity.getContactInfo())) {
                    entity.setConnection(entity.getContactInfo().get(0).getContrcts());
                    entity.setConnectionPhone(entity.getContactInfo().get(0).getContrctsNumber());
                }
                syncContact(entity);
                break;
        }
    }

    /**
     * 同步装货时间
     */
    private void syncDate(CargoPublishEntity entity) {
        mEntity = entity;
        if (mEntity.getBeginTime() == 0) {
            binding.tvReleaseCargoLoadDate.setText("");
            return;
        }else {
            if (mEntity.getStartPointTime()==25?DateUtils.getCustomizeDayNight(0,mEntity.getBeginTime()).getTime()<DateUtils.getCustomizeDayNight(0, TimeUtil.currentTimeMillis()).getTime():mEntity.getBeginTime()<TimeUtil.currentTimeMillis()){
                binding.tvReleaseCargoLoadDate.setText("");
                return;
            }
        }
        //设置装货时间
        binding.tvReleaseCargoLoadDate.setText(CargoConstant.stampFormatListLoadTime(
                mEntity.getBeginTime(), mEntity.getStartPointTime(),
                mEntity.getEndTime(), mEntity.getEndPointTime()));
    }

    /**
     * 设置货源信息
     */
    private void syncGoods(CargoPublishEntity entity) {
        mEntity = entity;
//        if (TextUtils.isEmpty(mEntity.getGoodsModeName())) {
//            binding.tvReleaseCargoCargoInfo.setText("");
//            return;
//        }
        StringBuilder builder = new StringBuilder();
        String name = entity.getGoodsModeName();
        if (!TextUtils.isEmpty(name)) {
            if (name.contains("/")) {
                name = name.substring(name.indexOf("/") + 1);
            }
            builder.append(name);
        }
        if (!TextUtils.isEmpty(mEntity.getPackageModeName())) {
            if (!TextUtils.isEmpty(name)) {
                builder.append("/");
            }
            builder.append(mEntity.getPackageModeName());
        }
        if (mEntity.getGoodsWeight() != 0) {
            if (builder.length() != 0){
                builder.append("/");
            }
            builder.append(NumberUtil.trim0(mEntity.getGoodsWeight())).append("吨");
        }
        if (mEntity.getGoodsVolume() != 0) {
            builder.append("/").append(NumberUtil.trim0(mEntity.getGoodsVolume())).append("方");
        }
        binding.tvReleaseCargoCargoInfo.setText(builder.toString());
        //计算总运费
        adjustTotalFreight();
    }

    /**
     * 同步费用要求
     */
    private void syncCost(CargoPublishEntity entity) {
        //2.0.8 删除信息费，改为展示支付方式
        mEntity = entity;
        String payType;
        if (!TextUtils.isEmpty(mEntity.getPayType())) {
            payType = String.format("/%s", mEntity.getPayType());
        } else {
            payType = "";
        }
        binding.tvReleaseCargoPrice.setText(String.format("运费单价 ¥%s%s",
                NumberUtil.trim0(mEntity.getFreight()),
                payType));
        //计算总运费
        adjustTotalFreight();
    }

    /**
     * 同步报价要求
     */
    private void syncOffer(CargoPublishEntity entity) {
        mEntity = entity;
        StringBuilder builder = new StringBuilder();
        if (mEntity.getQuotationQualification() != null && mEntity.getQuotationQualification().length == 3) {
            for (int i = 0; i < mEntity.getQuotationQualification().length; i++) {
                if (i == 0 && mEntity.getQuotationQualification()[0]) {
                    builder.append("/").append("企业");
                } else if (i == 1 && mEntity.getQuotationQualification()[1]) {
                    builder.append("/").append("团队");
                } else if (i == 2 && mEntity.getQuotationQualification()[2]) {
                    builder.append("/").append("个人（司机）");
                }
            }
        }
        binding.tvReleaseCargoOffer.setText(builder.length() == 0 ? "" : builder.substring(1));
    }

    /**
     * 同步联系人信息
     */
    private void syncContact(CargoPublishEntity entity) {
        mEntity = entity;
        //提交数据时检查是否填写联系人
        if (ArrayUtil.isNotNullAndEmpty(entity.getContactInfo())) {
            binding.tvReleaseCargoContact.setText(String.format("%s/%s%s",
                    entity.getContactInfo().get(0).getContrcts(),
                    entity.getContactInfo().get(0).getContrctsNumber(),
                    entity.getContactInfo().size() == 1 ? "" : "等"));
        } else {
            binding.tvReleaseCargoContact.setText("");
        }
    }

    /**
     * 同步更多数据
     */
    private void syncMoreData(CargoPublishEntity entity) {
        mEntity = entity;
        //发票要求信息匹配检测
        if (mEntity.isInvoiceChanges()) {
            mEntity.setInvoiceNo("");
            mEntity.setInvoice("");
            mEntity.setTariff(null);
            showFieldAlterDialog();
        }
        //整体判断内容
        if (!TextUtils.isEmpty(mEntity.getProjectName()) || mEntity.getProjectAddress() != null
                || !TextUtils.isEmpty(mEntity.getProjectDesc()) || !TextUtils.isEmpty(mEntity.getTransportReq())
                || !TextUtils.isEmpty(mEntity.getPartyAAgreement()) || !TextUtils.isEmpty(mEntity.getPartyBAgreement())
                || !TextUtils.isEmpty(mEntity.getBreachOfContract()) || !TextUtils.isEmpty(mEntity.getTerminationAgreement())
                || mEntity.getRequire() != 0 || !TextUtils.isEmpty(mEntity.getInvoicingCompanyName())
                || (!TextUtils.isEmpty(mEntity.getInvoice()) && mEntity.getTariff() != null && !TextUtils.isEmpty(mEntity.getInvoiceNo()))) {
            binding.tvReleaseCargoMore.setText("已填写");
        } else {
            binding.tvReleaseCargoMore.setText("");
        }
    }

    /**
     * 因 2.0.4 发票要求字段调整，提示用户重新选择
     */
    private void showFieldAlterDialog() {
        new RoundDialog.Builder(this)
                .title("提示")
                .content("平台发票要求已调整，使用历史货源发布需重新选择该信息")
                .confirm("我知道了")
                .singleBtn(true)
                .confirmCallback(v -> {
                    if (mEntity != null) {
                        mEntity.setInvoiceChanges(false);
                    }
                })
                .contentGravity(Gravity.CENTER)
                .cancelable(false)
                .show();
    }

    /**
     * 同步收货/发货
     */
    private void syncLocation(Intent data) {
        if (data == null) return;
        CargoPublishEntity.LocationEntity locationEntity = data.getParcelableExtra(RouterKey.DATA);
        if (locationEntity == null) return;
        mLocationList.set(mLocationIndex, locationEntity);
        mLocationAdapter.notifyDataSetChanged();
        //重设缓存数据
        viewModel.setCacheLocation(locationEntity.getCacheIndex(), locationEntity);
    }

    /**
     * 计算运程
     */
    private void calculateLineDistance() {
        viewModel.calculateLineDistance(mLocationList, mEntity.getLoadModeNo());
    }

    /**
     * 调整运费(更改了货物信息和运费信息之后计算
     */
    private void adjustTotalFreight() {
        if (mEntity.getFreight() == 0) {
            mEntity.setTotalFreight(0);
            binding.tvReleaseCargoFreight.setText(R.string.default_release_cargo_price);
            return;
        }
        //根据运费类型计算运费
        double total;
        switch (mEntity.getFreightMode()) {
            case CargoPublishEntity.FreightMode.MODE_WEIGHT:
                if (mEntity.getGoodsWeight() == 0) {
                    total = 0;
                    binding.tvReleaseCargoFreight.setText(R.string.default_release_cargo_price);
                } else {
                    total = mEntity.getGoodsWeight() * mEntity.getFreight();
                    binding.tvReleaseCargoFreight.setText(String.format("%s元", NumberUtil.trim0(total)));
                }
                mEntity.setTotalFreight(total);
                break;
            case CargoPublishEntity.FreightMode.MODE_VOLUME:
                if (mEntity.getGoodsVolume() == 0) {
                    total = 0;
                    binding.tvReleaseCargoFreight.setText(R.string.default_release_cargo_price);
                } else {
                    total = mEntity.getGoodsVolume() * mEntity.getFreight();
                    binding.tvReleaseCargoFreight.setText(String.format("%s元", NumberUtil.trim0(total)));
                }
                mEntity.setTotalFreight(total);
                break;
        }
    }
}